#__*__coeding:utf-8__*__
#!/usr/share/python
'''
---------------------------------------------------------------- 
 版权所有。  
 
 文件名：
 文件功能描述： 
 author：
 时间：
--------------------------------------------------------------- 
'''

import time
from DB.dbbase import dbbase
from Base.tools import tools
from flask import Flask

log=Flask(__name__)

_db=dbbase()

class data_insert:

    def removelogdateid(self,*args):
        result=[]
        for i in args[0]:
            i=list(i)
            i.remove(i[0])
            i[1]=str(i[1]).split(' ')[0]
            result.append(tuple(i))
        return result

    def removedataid(self,*args):
        result=[]
        for i in args[0]:
            i=list(i)
            i.remove(i[0])
            result.append(tuple(i))
        return result

    def insert_allcont_logdate(self,*args):
        sql='INSERT INTO nginx_log_logdate(allcunt,logdate,logforwardhost) VALUES (%s,%s,%s)'
        value=args[0]
        sql_date=self.mysql_getmay(sql='SELECT * FROM nginx_log_logdate;')
        _db.end('commit')
        sql_dates=self.removelogdateid(sql_date)
        if value not in sql_dates:
            execut = _db.insertOne(sql, value)
            _db.end('commit')
            return True
        else:
            return False

    def Mentionlogdatefields(self,*args):
        '''
        Mention logdate fields
        :return:date logdate list <type:list>
        '''
        logdate=[]
        for i in args[0]:
            if len(i)==6:
                logdate.append(i[5])
            elif len(i)==4:
                logdate.append(i[3])
        return logdate

    def Getsthecurrentoperatingdatadateid(self):
        '''
        Gets the current operating data date ID
        :return:Gets the current operating data date ID <type: int>
        '''
        logdateids=self.get_logdate_limitid()
        logdateid=logdateids[0]
        return logdateid

    def Ipdataassembly(self,*args):
        '''
        Each access to the IP data collection's current operation log time id
        :param args: ip date set
        :return:ip date set <type:list[list]>
        '''
        value=[]
        for list_value in args[0]:
            for dict_value in list_value:
                dict_tuple=(dict_value['area'],dict_value['location'],dict_value['s_IP'],dict_value['s_PV'])
                dict_list=list(dict_tuple)
                dict_list.append(self.Getsthecurrentoperatingdatadateid())
                value.append(dict_list)
        return value

    def Getalldate(self,tablename):
        '''
        Get all IP date
        :return: IP date tulpe <type:tulpe>
        '''
        sql='SELECT * FROM %s;'%tablename
        execut = _db.getAll(sql)
        return execut

    def insert_ipdata(self,*args):
        value = self.Ipdataassembly(args)
        if value not in self.removedataid(self.Getalldate(tablename='nginx_log_access_ip')):
            sql = 'INSERT INTO nginx_log_access_ip(s_area,s_location,s_IP,s_UV,logdate_id) VALUES (%s,%s,%s,%s,%s)'
            ipdata_inser=_db.insertMany(sql,value)
            _db.end('commit')
            return True
        else:
            return False

    def Access_timedateassembly(self,*args):
        values = []
        logdate = self.get_logdate_limitid()
        for i in args[0]:
            ti=i[0]
            ti=ti.replace("Jan", "01").replace("Feb", "02").replace("Mar", "03")\
             .replace("Apr", "04").replace("May", "05").replace("Jun", "06")\
             .replace("Jul", "07").replace("Aug", "08").replace("Sep", "09")\
             .replace("Oct", "10").replace("Nov", "11").replace("Dec", "12")
            toim = time.strptime(ti, '%d/%m/%Y:%H')
            toi= time.strftime('%Y-%m-%d  %H:%M:%S',toim)
            values.append((toi, i[1],logdate[0]))
        return values

    def insert_access_time(self,*args):
        values = self.Access_timedateassembly(args[0])
        if values not in self.removedataid(self.Getalldate(tablename='nginx_log_access_time')):
            values=self.Access_timedateassembly(args[0])
            sql="INSERT into nginx_log_access_time(s_access_time,s_access_time_cunt,logdate_id) VALUES (%s,%s,%s)"
            execute = _db.insertMany(sql,values)
            _db.end(option='commit')
            return True
        else:
            return False

    def dateassembly(self,*args):
        logdateid=self.get_logdate_limitid()
        results=[]
        for i in args[0]:
            resutl=i+logdateid
            results.append(resutl)
        return results

    def insert_access_referer(self,*args):
        values = self.dateassembly(args[0])
        if values not in self.removedataid(self.Getalldate('nginx_log_access_referer')):
            sql="INSERT INTO nginx_log_access_referer(s_referer_addr,s_referer_cunt,logdate_id) VALUES (%s,%s,%s)"
            execute=_db.insertMany(sql,values)
            _db.end(option='commit')
            return True
        else: return False

    def insert_access_agent(self,*args):
        values = self.dateassembly(args[0])
        if values not in self.removedataid(self.Getalldate('nginx_log_access_agent')):
            sql="INSERT INTO nginx_log_access_agent(s_Device_type,s_Device_cunt,logdate_id) VALUES (%s,%s,%s)"
            execuet=_db.insertMany(sql,values)
            _db.end(option='commit')
            return True
        else:
            return False

    def insert_access_forwarded(self,*args):
        values = self.dateassembly(args[0])
        if values not in self.removedataid(self.Getalldate('nginx_log_access_forwarded')):
            sql="INSERT INTO nginx_log_access_forwarded(forwarded_for,forwarded_cunt,logdate_id) VALUES (%s,%s,%s)"
            execuet=_db.insertMany(sql,values)
            _db.end(option='commit')
            log.logger.critical('insert_access_forwarded %s successful!')
            return True
        else:
            return False

    def get_logdate_limitid(self):
        sql='SELECT id FROM nginx_log_logdate ORDER BY id DESC LIMIT 1'
        result=_db.getOne(sql)
        _db.end(option='commit')
        return result


    def mysql_getone(self,sql):
        result=_db.getOne(sql)
        _db.end(option='commit')
        return result

    def mysql_getmay(self,sql):
        result=_db.getAll(sql)
        _db.end('commit')
        return result

    def mysql_coles(self):
        _db.dispose()
        return True
